package cn.dzh.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象保存到Redis中
     * 
     * @param key Redis key
     * @param value 对象
     * @throws JsonProcessingException 如果序列化过程中出错
     */
    public void setObject(String key, Object value) throws JsonProcessingException {
        String jsonValue = mapper.writeValueAsString(value);
        stringRedisTemplate.opsForValue().set(key, jsonValue);
    }

    /**
     * 从Redis中获取对象
     * 
     * @param key Redis key
     * @param clazz 返回对象的类
     * @param <T> 类型参数
     * @return 返回的对象
     * @throws JsonProcessingException 如果反序列化过程中出错
     */
    public <T> T getObject(String key, Class<T> clazz) throws JsonProcessingException {
        String jsonValue = stringRedisTemplate.opsForValue().get(key);
        if (jsonValue == null) {
            return null;
        }
        return mapper.readValue(jsonValue, clazz);
    }

    /**
     * 设置简单的字符串值
     * 
     * @param key Redis key
     * @param value 值
     */
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 从Redis中获取字符串值
     * 
     * @param key Redis key
     * @return 值
     */
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 删除Redis中的键值对
     * 
     * @param key Redis key
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }
}
